﻿#include "SVTemplateView.h"

SVTemplateView::SVTemplateView(QWidget *parent)
    : QWidget(parent)
    , mTemplatePictureList(new QListView(this))
    , mAddTemplateButton(new ElaIconButton(ElaIconType::Plus, this))
    , mRemoveTemplateButton(new ElaIconButton(ElaIconType::TrashCan, this))
{
    mTemplatePictureList->setViewMode(QListView::IconMode);
    mTemplatePictureList->setIconSize(QSize(256, 256));
    mTemplatePictureList->setGridSize(QSize(300, 300));
    mTemplatePictureList->setResizeMode(QListView::Adjust);
    mTemplatePictureList->setSpacing(10);
    mTemplatePictureList->setSelectionBehavior(QAbstractItemView::SelectItems);
    mTemplatePictureList->setSelectionMode(QAbstractItemView::ExtendedSelection);

    QHBoxLayout *buttonLayout = new QHBoxLayout;
    buttonLayout->addStretch();
    buttonLayout->addWidget(mAddTemplateButton);
    buttonLayout->addWidget(mRemoveTemplateButton);
    buttonLayout->setStretch(0, 3);
    buttonLayout->setStretch(1, 1);
    buttonLayout->setStretch(2, 1);

    QVBoxLayout *layout = new QVBoxLayout(this);
    layout->addWidget(mTemplatePictureList);
    layout->addLayout(buttonLayout);
    layout->setStretch(0, 9);
    layout->setStretch(1, 1);

    connect(
        mAddTemplateButton, &ElaIconButton::clicked, this, &SVTemplateView::addTemplateRequested);
    connect(mRemoveTemplateButton,
            &ElaIconButton::clicked,
            this,
            &SVTemplateView::onRemoveTemplateClicked);
}

void SVTemplateView::setTemplateListModel(QAbstractItemModel *model)
{
    mTemplatePictureList->setModel(model);
}

void SVTemplateView::onRemoveTemplateClicked()
{
    QModelIndexList selectedIndexes = mTemplatePictureList->selectionModel()->selectedIndexes();
    QList<int> rows;
    for (const QModelIndex &selectIndex : selectedIndexes) {
        if (!rows.contains(selectIndex.row())) {
            rows.append(selectIndex.row());
        }
    }
    emit removeTemplateRequested(rows);
}
